package com.xzq.erp.controller;

import com.xzq.erp.aspect.ApiOperationLog;
import com.xzq.erp.domain.po.SysPermission;
import com.xzq.erp.service.ISysPermissionService;
import com.xzq.erp.utils.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 系统权限表 前端控制器
 * </p>
 *
 * @author xzq
 * @since 2025-05-19
 */
@RestController
@RequestMapping("/permission")
@Tag(name = "权限相关接口")
@RequiredArgsConstructor
public class SysPermissionController {

    private final ISysPermissionService permissionService;

    /**
     * 获取所有权限列表
     */
    @GetMapping
    @Operation(summary = "获取所有权限列表")
    @ApiOperationLog(description = "获取所有权限列表")
    @PreAuthorize("hasAuthority('sys:permission:list') || hasRole('ADMIN')")
    public Response<List<SysPermission>> getPermissionList() {
        return Response.success(permissionService.list());
    }

    /**
     * 根据用户ID获取权限列表
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "根据用户ID获取权限列表")
    @ApiOperationLog(description = "根据用户ID获取权限列表")
    @PreAuthorize("hasAuthority('sys:permission:list') || hasRole('ADMIN')")
    public Response<List<SysPermission>> getPermissionsByUserId(
            @Parameter(description = "用户ID") @PathVariable Integer userId) {
        return Response.success(permissionService.getPermissionsByUserId(userId));
    }

    /**
     * 根据角色ID获取权限列表
     */
    @GetMapping("/role/{roleId}")
    @Operation(summary = "根据角色ID获取权限列表")
    @ApiOperationLog(description = "根据角色ID获取权限列表")
    @PreAuthorize("hasAuthority('sys:permission:list') || hasRole('ADMIN')")
    public Response<List<SysPermission>> getPermissionsByRoleId(
            @Parameter(description = "角色ID") @PathVariable Integer roleId) {
        return Response.success(permissionService.getPermissionsByRoleId(roleId));
    }

    /**
     * 保存角色权限关系
     */
    @PostMapping("/role/{roleId}")
    @Operation(summary = "保存角色权限关系")
    @ApiOperationLog(description = "保存角色权限关系")
    @PreAuthorize("hasAuthority('sys:permission:assign') || hasRole('ADMIN')")
    public Response<Void> saveRolePermissions(
            @Parameter(description = "角色ID") @PathVariable Integer roleId,
            @RequestBody List<Integer> permissionIds) {
        permissionService.saveRolePermissions(roleId, permissionIds);
        return Response.success();
    }
}
